package com.freecloud.javabasics.design.proxy.jdk;

import com.freecloud.common.FileUtils;
import com.freecloud.javabasics.design.proxy.FindJob;
import com.freecloud.javabasics.design.proxy.Student;
import sun.misc.ProxyGenerator;

import java.lang.reflect.Proxy;

/**
 * 使用原生JDK实现动态代理，需要代理类实现InvocationHandler接口
 * @Author: maomao
 * @Date: 2019-11-22 11:08
 */
public class JdkProxyTest {

    public static void main(String[] args) {

        Class<?> clazz = Student.class;

        JdkProxy proxy = new JdkProxy(new Student());

        //创建被代理新类，如直接通过类调用，无法获取具体方法，没办法执行
        //Object object = Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),proxy);

        //强转，会报错，因JDK动态代理，需要一个接口《clazz.getInterfaces()》第二个参数
        //Student student = (Student) Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),proxy);
        //student.findJob();

        //JDK动态代理方式，只可以代理行为，那是否还有其他方式
        //我不想实现写接口，只是单纯给某个类实现代理，当然是有的，可以看Cglib的例子
        FindJob findJob = (FindJob) Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),proxy);
        findJob.findJob();

        //输出新生成的代理类，查看具体内容
        byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0",Student.class.getInterfaces());

        FileUtils.outFile(classFile,"/Users/maomao/Downloads/JdkProxy.class");
    }
}
